package cn.b.sky.user;

import cn.b.sky.common.utils.AjaxUtil;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AuthorityAccessDeniedHandlerImpl implements AccessDeniedHandler {

  private String errorPage;

  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response,
                     AccessDeniedException accessDeniedException) throws IOException, ServletException {
    boolean isAjax = AjaxUtil.isAjax(request);
    if (!response.isCommitted()) {
      // 如果是ajax请求
      if (isAjax) {
        //request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);

        // Set the 403 status code.
        //response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        String contentType = "application/json;charset=UTF-8";
        response.setContentType(contentType);
        String jsonObject = JSONObject.toJSONString(AjaxUtil.ajaxError(LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "noright_view.C")));
        PrintWriter out = response.getWriter();
        out.print(jsonObject);
        out.flush();
        out.close();
        return;
      }
      // 非ajax
      if (errorPage != null) {
        // Put exception into request scope (perhaps of use to a
        // view)
        request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);

        request.setAttribute("accessDefinedMessage",
            LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),SecurityContextUtil.getLanguageCode(), "noright_view.C"));
        // Set the 403 status code.
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        // forward to error page.
        RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
        dispatcher.forward(request, response);
      } else {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
      }

    }
  }

  /**
   * The error page to use. Must begin with a "/" and is interpreted relative
   * to the current context root.
   * 
   * @param errorPage
   *            the dispatcher path to display
   * 
   * @throws IllegalArgumentException
   *             if the argument doesn't comply with the above limitations
   */
  public void setErrorPage(String errorPage) {
    if ((errorPage != null) && !errorPage.startsWith("/")) {
      throw new IllegalArgumentException("errorPage must begin with '/'");
    }

    this.errorPage = errorPage;
  }
}
